package com.framework.test.core;

import com.framework.test.exceptions.AutomationException;
import com.framework.test.utils.ConfigurationManager;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;

import java.io.*;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class CSVDataProvider {

    @DataProvider(name = "csvReader")
    public static Object[][] provideData(Method method, ITestContext context) throws IOException, AutomationException {
        String className = method.getDeclaringClass().getSimpleName();
        String methodName = method.getName();
        String testDataPath = ConfigurationManager.getProperty("testDataPath");

        // 尝试多个路径查找CSV文件
        String fileName = className.concat("-").concat(methodName).concat(".csv");
        InputStream inputStream = findCsvFile(testDataPath, fileName);

        if (inputStream != null) {
            List<String[]> data = new ArrayList<>();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                String headerLine = br.readLine();
                if (headerLine == null) {
                    throw new IOException("CSV file is empty or cannot be read");
                }

                String[] headers = headerLine.split(",");
                int columnCount = headers.length;

                // 参数化文件至少有caseTitle和runFlag列
                if (columnCount < 2) {
                    throw new IOException("CSV file must have at least caseTitle and runFlag columns");
                }

                // 第一列必须为caseTitle
                if (!headers[0].trim().equalsIgnoreCase("caseTitle")) {
                    throw new IOException("First column must be caseTitle");
                }

                // 最后一列必须为runFlag
                if (!headers[columnCount - 1].trim().equalsIgnoreCase("runFlag")) {
                    throw new IOException("Last column must be runFlag");
                }

                while ((line = br.readLine()) != null) {
                    String[] parts = line.split(",");

                    // 如果runFlag = Y时,才读取参数化文件
                    if (parts.length == columnCount && parts[columnCount - 1].trim().equalsIgnoreCase("Y")) {
                        String[] rowData = new String[columnCount - 1];
                        for (int i = 0; i < columnCount - 1; i++) {
                            rowData[i] = parts[i].trim();
                        }
                        data.add(rowData);
                    }
                }
            }
            return data.toArray(new Object[0][]);
        }
        return null;
    }

    /**
     * 在多个路径中查找CSV文件
     *
     * @param testDataPath 基础测试数据路径
     * @param fileName     文件名
     * @return InputStream 或 null
     */
    private static InputStream findCsvFile(String testDataPath, String fileName) {
        String[] searchPaths = {
                testDataPath.concat(System.getProperty("file.separator")).concat(fileName),
                testDataPath.concat("/").concat(fileName),
                fileName,
                "testData/".concat(fileName)
        };

        for (String path : searchPaths) {
            InputStream stream = CSVDataProvider.class.getClassLoader().getResourceAsStream(path);
            if (stream != null) {
                return stream;
            }
        }
        return null;
    }
}
